package com.sochinchou.res.components;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;



public class MyProvider extends ContentProvider{

	public static final String TAG = "=== MyProvider ===";
	public static final String AUTHORITY = "com.myproviders.provider";

    private static final UriMatcher uriMatcher;
    static{
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY, "directory", Catalog.ITEMS);
        uriMatcher.addURI(AUTHORITY, "directory/#", Catalog.ITEM_ID); 
        uriMatcher.addURI(AUTHORITY, "article", Article.ITEMS);
        uriMatcher.addURI(AUTHORITY, "article/#", Article.ITEM_ID); 
    }
	
        
    //--------------------------- Database Helper ----------------------------------------
   
    private static class DatabaseHelper extends SQLiteOpenHelper{

        private static final String DATABASE_NAME = "knowledge_database.db";
        private static final int DATABASE_VERSION = 1;
        
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);						
		}

		@Override
		public void onCreate(SQLiteDatabase db) {			
			db.execSQL("CREATE TABLE " + Catalog.TABLE_NAME + " (" 
					+ Catalog._ID + " INTEGER PRIMARY KEY," 
					+ Catalog.CATALOG_ID + " TEXT,"
					+ Catalog.CATALOG_NAME+ " TEXT,"
					+ Catalog.PARENT_ID + " TEXT,"
					+ Catalog.ADDTIME + " TEXT,"
					+ Catalog.UPDATETIME + " TEXT);");
			
			db.execSQL("CREATE TABLE " + Article.TABLE_NAME + " (" 
					+ Article._ID + " INTEGER PRIMARY KEY," 
					+ Article.ARTICLE_ID + " TEXT,"
					+ Article.PARENT_ID+ " TEXT,"
					+ Article.CATALOG_ID + " TEXT,"
					+ Article.TITLE + " TEXT,"
					+ Article.IMAGES + " TEXT,"
					+ Article.CONTENT + " TEXT,"
					+ Article.TTS_CONTENT + " TEXT,"
					+ Article.ISFAV + " TEXT,"
					+ Article.ADDTIME + " TEXT," 
					+ Article.UPDATETIME + " TEXT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + Catalog.TABLE_NAME);
            db.execSQL("DROP TABLE IF EXISTS " + Article.TABLE_NAME);
            onCreate(db);			
		}
    	
    }
    //----------------------------------------------------------------------
    
       
    private SQLiteDatabase mDb;
       
	// ---------------------------- onCreate ------------------------------
	@Override
	public boolean onCreate() {
		Context context = getContext();
		DatabaseHelper helper = new DatabaseHelper(context);
		mDb = helper.getWritableDatabase();
		//Log.d(TAG, "knowledge provider onCreate() >>>>>");
		return (mDb == null) ? false : true;
	}

	
	// ---------------------------- query ------------------------------
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		//Log.d(TAG, "query() >>>>> " + uri);
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

		
		switch(uriMatcher.match(uri)){		
		case Catalog.ITEM_ID:
			qb.setTables(Catalog.TABLE_NAME);
			qb.appendWhere(BaseColumns._ID + "=" + uri.getPathSegments().get(1));
			break;
			
		case Catalog.ITEMS:
			qb.setTables(Catalog.TABLE_NAME);
			if(TextUtils.isEmpty(sortOrder))
				sortOrder = Catalog.DEFAULT_SORT_ORDER;
            break;
            
		case Article.ITEM_ID:
			qb.setTables(Article.TABLE_NAME);
			qb.appendWhere(BaseColumns._ID + "=" + uri.getPathSegments().get(1));
			break;
			
		case Article.ITEMS:
			qb.setTables(Article.TABLE_NAME);
			if(TextUtils.isEmpty(sortOrder))
				sortOrder = Article.DEFAULT_SORT_ORDER;
			break;
			
        default:
        	 throw new IllegalArgumentException("Unknown URI : " + uri);           
		}		
		//---register to watch a content URI for changes---
		Cursor c = qb.query(mDb, projection, selection, selectionArgs, null, null, sortOrder);   // requery is deprecated
		c.setNotificationUri(getContext().getContentResolver(), uri);		
		return c;
	}

	
	// ---------------------------- getType ------------------------------
	@Override
	public String getType(Uri uri) {
		//Log.d(TAG, "getType() >>>>> " + uri);
		switch(uriMatcher.match(uri)){		
		case Catalog.ITEM_ID:
			return Catalog.CONTENT_ITEM_TYPE;
		case Catalog.ITEMS:
			return Catalog.CONTENT_TYPE;
		case Article.ITEM_ID:
			return Article.CONTENT_ITEM_TYPE;
		case Article.ITEMS:
			return Article.CONTENT_TYPE;		
		default:
			throw new IllegalArgumentException("Unknown URI : " + uri);		
		}
	}

	
	// ---------------------------- insert ------------------------------
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		//Log.d(TAG, "insert() >>>>> " + uri);
		long rowId = 0L;
		Uri resultUri = null;
		
		switch(uriMatcher.match(uri)){
		case Catalog.ITEMS:
			rowId = mDb.insert(Catalog.TABLE_NAME, null, values);
			if(rowId > 0){
				resultUri = ContentUris.withAppendedId(Catalog.CONTENT_URI, rowId);
			}
			break;
			
		case Article.ITEMS:
			rowId = mDb.insert(Article.TABLE_NAME, null, values);
			if(rowId > 0){
				resultUri = ContentUris.withAppendedId(Article.CONTENT_URI, rowId);
			}
			break;
			
		default:
			throw new IllegalArgumentException("Unknown URI : " + uri);	
		}
		
		if(resultUri != null){
			getContext().getContentResolver().notifyChange(uri, null);
			return resultUri;
		}
		throw new SQLException("Failed to insert into : " + uri);
			
	}

	
	// ---------------------------- delete ------------------------------
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		//Log.d(TAG, "delete() >>>>> " + uri);
		int count = 0;
		
		switch(uriMatcher.match(uri)){
		case Catalog.ITEM_ID:
			count = mDb.delete(Catalog.TABLE_NAME, 
					BaseColumns._ID + "=" + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), 
					selectionArgs);
			break;
			
		case Catalog.ITEMS:
			count = mDb.delete(Catalog.TABLE_NAME, selection, selectionArgs);
			break;
			
		case Article.ITEM_ID:
			count = mDb.delete(Article.TABLE_NAME, 
					BaseColumns._ID + "=" + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), 
					selectionArgs);
			break;
			
		case Article.ITEMS:
			count = mDb.delete(Article.TABLE_NAME, selection, selectionArgs);
			break;		
			
		default:
			throw new IllegalArgumentException("Unknown URI : " + uri);		
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	
	// ---------------------------- update ------------------------------
	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		//Log.d(TAG, "update() >>>>> " + uri);
		int count = 0;
		
		switch(uriMatcher.match(uri)){
		case Catalog.ITEM_ID:
			count = mDb.update(Catalog.TABLE_NAME, values, 
					BaseColumns._ID + "=" + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), 
					selectionArgs);
			break;
			
		case Catalog.ITEMS:
			count = mDb.update(Catalog.TABLE_NAME, values, selection, selectionArgs);
			break;
			
		case Article.ITEM_ID:
			count = mDb.update(Article.TABLE_NAME, values, 
					BaseColumns._ID + "=" + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), 
					selectionArgs);
			break;
			
		case Article.ITEMS:
			count = mDb.update(Article.TABLE_NAME, values, selection, selectionArgs);
			break;			
			
		default:
			throw new IllegalArgumentException("Unknown URI : " + uri);		
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
	
	
	/*
        if (c.moveToFirst()) {
            do {

            } while (c.moveToNext());
        }
	 */
	
	
	public static final class Catalog implements BaseColumns {

		private Catalog(){}
		
		public static final String CATALOG_ID = "catalog_id";
		public static final String CATALOG_NAME = "catalog_name";
		public static final String PARENT_ID = "parent_id";
		public static final String ISCATALOG = "iscatalog";
		public static final String ADDTIME = "addtime";
		public static final String UPDATETIME = "updatetime";
		

		public static final String TABLE_NAME = "directory_table";
		public static final Uri CONTENT_URI = Uri.parse("content://" + MyProvider.AUTHORITY + "/directory");
		public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.roadrover.directory";
		public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.roadrover.directory";
		public static final int ITEMS = 101;
		public static final int ITEM_ID = 102;
		public static final String DEFAULT_SORT_ORDER = _ID +" ASC"; //desc
	}
	
	
	public static final class Article implements BaseColumns {

		private Article(){}
		
		public static final String ARTICLE_ID = "article_id";
		public static final String PARENT_ID = "parent_id";
		public static final String CATALOG_ID = "catalog_id";	
		public static final String TITLE = "title";
		public static final String IMAGES = "images";
		public static final String CONTENT = "content";
		public static final String TTS_CONTENT = "tts_content";
		public static final String ISFAV = "isfav";
		public static final String ADDTIME = "addtime";
		public static final String UPDATETIME = "updatetime";

		
		public static final String TABLE_NAME = "article_table";
		public static final Uri CONTENT_URI = Uri.parse("content://" + MyProvider.AUTHORITY + "/article");
		public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.roadrover.article";
		public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.roadrover.article";
		public static final int ITEMS = 201;
		public static final int ITEM_ID = 202;
		public static final String DEFAULT_SORT_ORDER = _ID + " ASC";
	}
	
}